<template>
  <div class="system_dict_content">
    <el-row :gutter="12">
      <el-col :span="6">
        <el-card shadow="hover" header="数据字典">
          <el-tree :default-expanded-keys="[0]" class="tree" :data="treeData.data" :props="defaultProps" @node-click="treeSelect" :style="{height:`${initHeight}px`}"/>
        </el-card>
      </el-col>
      <el-col :span="18">
        <el-card shadow="hover">
          <div class="system-user-search mb10">
            <pageSearch :searchformConfig="searchConfig" @handleQueryClick="handleQueryClick"
              @handleResetClick="handleResetClick" @handleAddClick="onOpenAddRole">
            </pageSearch>
          </div>

          <el-table-plus row-key="key" :max-height="initHeight-32" :pagination="pagination" :data="state.tableData.data" :columns="columns" :total="pagination.total"
            @page-change="handlePageChange" @prev-click="handlePageChange" @next-click="handlePageChange">
            
            <template #status="{ cellValue, row, column }">
              <el-tag class="ml-2" :type="row.status == 0 ? 'success' : 'danger'"
                :disable-transitions="true">{{row.status==0?'启用':'禁用'}}</el-tag>
            </template>

            <template #handle="{ cellValue, row, column }">
              <el-button :type="row.status == 0 ? 'danger' : 'success'" text size="small"
                v-if="state.tableData.auth.disenabled"
                @click="handleDisEnd({ cellValue, row, column })">{{ row.status == 0 ? '禁用' : '启用' }}</el-button>
              <el-button type="primary" size="small" text @click="handleEdit({ cellValue, row, column })" v-if="state.tableData.auth.edit">编辑</el-button>
              <el-button type="danger" size="small" text @click="handleDel({ cellValue, row, column })" v-if="state.tableData.auth.delete">删除</el-button>
            </template>
            <template #handleTitle>操作</template>
          </el-table-plus>
        </el-card>
      </el-col>
    </el-row>

    <DictForm ref="formRef" @on-load="handleQueryClick" />

  </div>

</template>

<script lang="ts" setup>
import { onMounted, reactive,computed ,ref} from 'vue'
import usePag from '/@/utils/table'
import { IForm } from '/@/types/form/search';
import pageSearch from '/@/components/search/page-search.vue';
import { success, confirm, error } from '/@/utils/msg'
import {dictApi} from '/@/api/system/dict'
import DictForm from '/@/views/system/dict/form.vue'

import {checkAuth} from '/@/utils/authFunction'


interface Tree {
  id:number
  label: string
  children?: Tree[]
}

const treeSelect = (data: Tree) => {
  state.tableData.params.parentid = data.id
  initTableData()
}
const treeData = reactive({
  data :[]
})

const loadTree = async()=>{
  const {code,data} = await dictApi().treeData()
  treeData.data = data as Tree[]
}

onMounted(()=>{
  loadTree()
})

const defaultProps = {
  children: 'children',
  label: 'label',
}

const initHeight = computed(() => {
  return document.documentElement.clientHeight - 210
})


interface TableDataState {
  tableData: {
    data: Array<any>,
    params: {
      parentid?: any
      keys: string
    },
    auth?:any
  }
}

const formRef = ref()

// 分页设置
const { PagStore } = usePag()

// 表头数据
const columns: any = [
  { label: "字典编码", prop: "key", width: '180', "show-overflow-tooltip": true },
  { label: "字典名称", prop: "label", width: '200' , "show-overflow-tooltip": true},
  {
    label: "字典状态", prop: "status", width: '100',slots: {
      customRender: "status"
    }
  },
  { label: "备注", prop: "remark", "show-overflow-tooltip": true },
  {
    label: "操作",
    fixed: "right",
    prop: "handle",
    width: "130",
    align: "right",
    slots: {
      customRender: "handle",
      customTitle: "handleTitle",
    },
  }
];

// 表格数据
const state = reactive<TableDataState>({
  tableData: {
    data: [],
    params: {
      parentid: 0,
      keys: ''
    },
    auth:{
      create:false,
      edit:false,
      delete:false,
      disenabled:false
    }
  }
});

// 分页
const pagination = reactive({ ...state.tableData.params, ...PagStore });

// 加载列表
const dataList = async () => {
  const { currentPage, pageSize } = { ...pagination }
  const param = { ...state.tableData.params, pageSize, currentPage }
  return await dictApi().dataList(param)
}


// 删除
const deleteRole = async (param) => {
  return await dictApi().delete(param)
}

// 初始化数据列表
const initTableData = async () => {
  const ds = await dataList()
  const { data, total } = { ...ds }
  pagination.total = total
  state.tableData.data = data
  state.tableData.auth.create = checkAuth('admin/dict/create')
  state.tableData.auth.edit = checkAuth('admin/dict/detail')
  state.tableData.auth.delete = checkAuth('admin/dict/delete')
  state.tableData.auth.disenabled = checkAuth('admin/dict/disenabled')
}

// 页面加载时
onMounted(() => {
  initTableData()
})

const colAttrs = {
  align: "left",
  border:'border'
};

// 删除角色
const handleDel = async (a: any) => {
  confirm(`此操作将永久删除用户帐户：“${a.row.username}”，是否继续?`).then(async () => {
    const { code, msg } = await deleteRole(a.row)
    if (code == 0 || code == true) {
      success(msg)
      initTableData()
    }
  }).catch(() => { })
}

// 编辑
const handleEdit = (a: any) => {
  formRef.value.openDialog(a.row, '编辑')
}

// 选择页面重新加载
const handlePageChange = (a: any) => {
  pagination.currentPage = a.currentPage
  initTableData()
}

// 打开新增角色弹窗
const onOpenAddRole = (a: any) => {
  formRef.value.openDialog({parentid:state.tableData.params.parentid})
}

// 查询
const handleQueryClick = (value: any) => {
  Object.assign(state.tableData.params,value)
  initTableData()
}

// 重置
const handleResetClick = () => {
  console.log('重置');
};

// 启用/禁用
const handleDisEnd = (a: any) => {
  confirm(`确认${a.row.status==0?'禁用':'启用'} ”${a.row.label}” 该操作?`).then(async()=>{
    const {code,msg} = await dictApi().disenabled(a.row.id)
    if ( code == 0 || code == true ) {
      success(msg)
      initTableData()
    } else {
      error(msg)
    }
  })
}

// 搜索配置
const searchConfig: IForm = {
  formItems: [
    { field: 'keys', type: 'input', label: '用户名', placeholder: '请输入 关键字' },
  ]
}

defineExpose({
  formRef
})

</script>

<style scoped>
.system_dict_content{
overflow: hidden;
}
.tree{
  overflow: auto;
}
</style>